package com.example.service.impl;

import com.example.mapper.ItemMapper;
import com.example.pojo.Item;
import com.example.pojo.ItemExample;
import com.example.pojo.ItemReq;
import com.example.service.EsItemService;
import com.example.service.ItemsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;

@Service
public class ItemsServiceImpl implements ItemsService {
    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private EsItemService esItemService;

    @Override
    public List<Item> queryAll() {
        return itemMapper.selectByExample(null);
    }

    @Override
    public boolean saveOrUpdate(Item item) {
        item.setUpdateTime(new Date());
        if (item.getId() == null){
            item.setCreateTime(new Date());
            int insert = itemMapper.insert(item);
            esItemService.save(item);
            return insert > 0;
        }else {
            int update = itemMapper.updateByPrimaryKey(item);
            esItemService.update(item);
            return update > 0;
        }
    }

    @Override
    public int deleteById(Long id) {
        esItemService.deleteById(id);
        return itemMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<Item> queryByCondition(ItemReq itemReq) {
        ItemExample example = new ItemExample();
        if (!ObjectUtils.isEmpty(itemReq.getKeyWord())){
            example.or().andTitleLike("%" + itemReq.getKeyWord() + "%");
            example.or().andSellPointLike("%" + itemReq.getKeyWord() + "%");
        }
        return itemMapper.selectByExample(example);
    }
}
